import axios from 'axios';

axios.defaults.timeout = process.env.VUE_APP_API_TIMEOUT;
axios.defaults.headers.common['Content-Type'] = process.env.VUE_APP_Content_Type;
axios.defaults.headers.common['X-Request-Token'] = process.env.VUE_APP_API_Request_Token;

//request 拦截器
axios.interceptors.request.use(
    config => {
      showLoading(config);
      return config;
    },
    err => {
      hideLoading(error.config);
      return Promise.reject(err);
    }
);

//response 拦截器
axios.interceptors.response.use(
    response => {
      hideLoading(response.config);
      return response;
    },
    error => {
      hideLoading(error.config);
      return Promise.reject(error)
    }
);

function req(options) {
  return new Promise((resolve, reject) => {
    axios(options).then(response => {
          if (response.data.code === 0) {
            resolve(response.data);
          } else {
            alert(response.data.msg);
          }
        },
        err => {
          reject(err);
          let msg = '请求失败！请检查网络';
          if (err.response) msg = err.response.data.msg;
          //alert(msg)
          console.log(msg);
        })
  });
}

function showLoading(config) {
  if (config.loading && window.$showLoading) {
    setTimeout(function () {
      window.$showLoading(config.loadingMsg || '')
    }, 200);
  }
}

function hideLoading(config) {
  if (config.loading && window.$hideLoading) {
    window.$hideLoading()
  }
}

export default {
  /**
   * 缓存对象
   */
  cacheData: new Map(),
  /**
   * get 请求
   * @param url 请求URL
   * @param data 请求数据
   * @param options 请求配置选项
   */
  get(url, data = null, options = null) {
    return req(Object.assign({
      url,
      method: 'get',
      params: data
    }, options));
  },

  /**
   * post 请求
   * @param url 请求URL
   * @param data 请求数据
   * @param options 请求配置选项
   */
  post(url, data = null, options = null) {
    return req(Object.assign({
      url,
      method: 'post',
      data
    }, options));
  },

  /**
   * 后台请求
   * @param options 请求配置选项
   */
  request(options) {
    return req(options);
  },
  /**
   * post 请求数据,并自动缓存,下次直接从缓存中读取
   * @param cacheName 缓存名称
   * @param url 请求URL
   * @param data 请求数据
   * @param options 请求配置选项
   */
  postCacheData(cacheName, url, data = null, options = null) {
    if (this.cacheData.get(cacheName) == null) {
      return this.post(url, data, options).then(r => {
        let data = r.data;
        this.cacheData.set(cacheName, data);
        return data;
      });
    } else {
      return Promise.resolve(this.cacheData.get(cacheName));
    }
  },
}